package freespiritsocial.io.user.util

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import freespiritsocial.io.user.base.App
import freespiritsocial.io.user.data.model.PlaceItem
import freespiritsocial.io.user.data.model.UploadPostEvent
import freespiritsocial.io.user.data.model.UploadPostEvent.Companion.PublishFailed
import freespiritsocial.io.user.data.model.bean.NotificationSettingPojo
import freespiritsocial.io.user.data.model.bean.UserInfo
import freespiritsocial.io.user.event.AppViewModel
import freespiritsocial.io.user.ext.gson
import java.util.*

object CacheUtil {
    var token: String = ""
        get() {
            val kv = MMKV.mmkvWithID("app")
            return kv.decodeString("token","")
        }
        set(value) {
            field = value
            val kv = MMKV.mmkvWithID("app")
            if (value.isEmpty()) {
                kv.encode("token","")
                setIsLogin(false)
                refreshUserInfo(null)
            } else {
                kv.encode("token",value)
                setIsLogin(true)
            }
        }

    /**
     * 获取保存的账户信息
     */
    fun getUser(): UserInfo? {
        val kv = MMKV.mmkvWithID("app")
        val userStr = kv.decodeString("user")
        return if (TextUtils.isEmpty(userStr)) {
            null
        } else {
            Gson().fromJson(userStr,UserInfo::class.java)
        }
    }

    /**
     * 获取当前地区
     */
    fun getCurPlace(): PlaceItem? {
        val kv = MMKV.mmkvWithID("app")
        val placeStr = kv.decodeString("Place")
        return if (TextUtils.isEmpty(placeStr)) {
            null
        } else {
            Gson().fromJson(placeStr,PlaceItem::class.java)
        }
    }

    fun setUploadEvent(uploadPostEvent: UploadPostEvent) {
        val kv = MMKV.mmkvWithID("app")
        val uploadEvents = getUploadEvents()
        uploadPostEvent.status = PublishFailed
        uploadEvents.add(uploadPostEvent)
        kv.encode("uploadList",gson.toJson(uploadEvents))
    }

    fun removeUploadEvent(uploadPostEvent: UploadPostEvent) {
        val kv = MMKV.mmkvWithID("app")
        val uploadEvents = getUploadEvents()
        uploadEvents.remove(uploadPostEvent)
        kv.encode("uploadList",gson.toJson(uploadEvents))
    }

    fun getUploadEvents(): ArrayList<UploadPostEvent> {
        val kv = MMKV.mmkvWithID("app")
        val uploadList = kv.decodeString("uploadList","")
        return gson.fromJson(uploadList,object: TypeToken<List<UploadPostEvent>>() {}.type) ?: arrayListOf()
    }

    /**
     * 设置账户信息
     */
    fun setUser(userResponse: UserInfo?) {
        val kv = MMKV.mmkvWithID("app")
        if (userResponse == null) {
            kv.encode("user","")
        } else {
            kv.encode("user",gson.toJson(userResponse))
        }
    }

    /**
     * 设置当前地区
     */
    fun setCurPlace(place: PlaceItem?) {
        val kv = MMKV.mmkvWithID("app")
        if (place == null) {
            kv.encode("Place","")
        } else {
            kv.encode("Place",gson.toJson(place))
        }

    }

    val appViewModel: AppViewModel by lazy { App.instance.getAppViewModelProvider().get(AppViewModel::class.java) }

    fun refreshUserInfo(it: UserInfo?) {
        setUser(it)
        appViewModel.userinfo.value = it
    }

    /**
     * 是否已经登录
     */
    fun isLogin(): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.decodeBool("login",false)
    }

    /**
     * 设置是否已经登录
     */
    private fun setIsLogin(isLogin: Boolean) {
        val kv = MMKV.mmkvWithID("app")
        kv.encode("login",isLogin)
    }

    /**
     * 是否是第一次登陆
     */
    fun isFirst(): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.decodeBool("first",true)
    }

    /**
     * 是否是第一次登陆
     */
    fun setFirst(first: Boolean): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.encode("first",first)
    }

    /**
     * 获取搜索历史缓存数据
     */
    fun getSearchHistoryData(): ArrayList<String> {
        val kv = MMKV.mmkvWithID("cache")
        val searchCacheStr = kv.decodeString("history")
        if (!TextUtils.isEmpty(searchCacheStr)) {
            return gson.fromJson(
                searchCacheStr,object: TypeToken<ArrayList<String>>() {}.type
            )
        }
        return arrayListOf()
    }

    fun setSearchHistoryData(searchResponseStr: String) {
        val kv = MMKV.mmkvWithID("cache")
        kv.encode("history",searchResponseStr)
    }

    /**
     * 获取通知设置
     */
    fun getNotificationSetting(): NotificationSettingPojo? {
        val kv = MMKV.mmkvWithID("cache")
        val notificationSetting = kv.decodeString("notificationSetting")
        if (!TextUtils.isEmpty(notificationSetting)) {
            return Gson().fromJson(notificationSetting,NotificationSettingPojo::class.java)
        }
        return null
    }

    fun setNotificationSetting(notificationSetting: NotificationSettingPojo?) {
        val kv = MMKV.mmkvWithID("cache")
        kv.encode("notificationSetting",gson.toJson(notificationSetting))
    }


    fun getUUID(): String {
        val kv = MMKV.mmkvWithID("app")
        var decodeString = kv.decodeString("uuid","")
        if (decodeString.isEmpty()) {
            decodeString = UUID.randomUUID().toString()
            kv.encode("uuid",decodeString)
        }
        return decodeString
    }
}